package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"net/http"
	"strconv"
)

func GetAllPapers(c *gin.Context) {
	data := make(map[string]interface{})
	code := e.SUCCESS

	data["lists"] = models.GetPapers()

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

func AddPapers(c *gin.Context) {

}

func AddPaper(c *gin.Context) {
	papers := make([]models.Paper, 0)
	_ = c.ShouldBindJSON(&papers)

	code := e.SUCCESS
	models.AddPaper(&papers)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func UpdatePaper(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS

	if models.ExistPaperByID(id) {
		code = e.SUCCESS
		json := make(map[string]string)
		_ = c.BindJSON(&json)
		content := json["content"]
		show := json["show"]
		tmp, _ := strconv.Atoi(show)
		data := make(map[string]interface{})
		data["content"] = content
		data["show"] = int8(tmp)
		models.UpdatePaper(id, data)
	} else {
		code = e.ERROR_NOT_EXIST
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func DeletePaper(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS
	if models.ExistPaperByID(id) {
		models.DeletePaper(id)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}